/*
 * 本类作用：测试
 * 
 * 作者：袁小杰
 * 博客：http://blog.csdn.net/undoner
 * GIT：https://git.oschina.net/undoner
 * QQ：15137281
 * 
 */
package org.mina.client;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.InputStream;
import java.net.Socket;

import org.mina.server.codec.MsgEntity;

public class StartClient {

	private static final String serverIP = "127.0.0.1";
	private static final int serverPort = 1024;

	public static void main(String[] args) {
		try {
			Socket socket = new Socket(serverIP, serverPort);

			// 获取输出流，用于客户端向服务器端发送数据
			DataOutputStream out = new DataOutputStream(socket
					.getOutputStream());

			// 获取输入流，用于接收服务器端发送来的数据
			InputStream in = socket.getInputStream();
			DataInputStream dis = new DataInputStream(in);

			MsgEntity me = new MsgEntity(RandomTools.getRandomStr());
			//out.writeInt(me.getLength());
			out.write(me.getContent().getBytes());
			out.flush();
			System.out.println("已发送数据："+me.getContent());

			// ---------------- 接收响应 开始 -----------------
			//byte[] head = new byte[Constant.HEADER_LEN];
			//int contentLength = dis.readInt()-Constant.HEADER_LEN;
			int contentLength = dis.readInt();
			byte[] content = new byte[contentLength];
			dis.read(content, 0, contentLength);

			System.out.println("返回数据：" + new String(content));
			in.close();
			in = null;
			dis.close();
			dis = null;
			// ---------------- 接收响应 结束 -----------------
			out.close();
			socket.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 4位字节数组转换为整型
	 * 
	 * @param b
	 * @return
	 */
	public static int byte2Int(byte[] b) {
		int intValue = 0;
		// int tempValue = 0xFF;
		for (int i = 0; i < b.length; i++) {
			intValue += (b[i] & 0xFF) << (8 * (3 - i));
			// System.out.print(Integer.toBinaryString(intValue)+" ");
		}
		return intValue;
	}

}
